package com.example.common.config.feign;

import com.example.common.constant.AuthServerConstant;
import com.example.common.constant.FeignConstant;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <p>
 *      Feign 配置
 *      1. 配置所有经过 feign 的请求，携带请求头 cookie
 *      2. 配置所有 feign 的请求，携带无需鉴权的标志位
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Slf4j
@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor () {
        log.info(">>>>>>>>>>>>>>>> common open feign init starting >>>>>>>>>>>>>>>>>>>>>");
        return template -> {
            // 将原始请求的 cookie 重新装配到 feign 的 header 中
            template.header(FeignConstant.SIGN_KEY, FeignConstant.SIGN_VAL);
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            if (Objects.nonNull(attributes)){
                ServletRequestAttributes att = (ServletRequestAttributes) attributes;
                HttpServletRequest request = att.getRequest();
                String header = request.getHeader(AuthServerConstant.GLOBAL_COOKIE_NAME);
                log.info(">>>>>>>>>>>>>>>> feign 获取 Cookie : {} <<<<<<<<<<<<<<<<<<<<", header);
                log.info(">>>>>>>>>>>>>>>> feign 请求路径 : {} <<<<<<<<<<<<<<<<<<<<", request.getRequestURL());
                template.header(AuthServerConstant.GLOBAL_COOKIE_NAME, header);
            }
        };
    }

}
